package com.alibaba.cirtus.ots.application.adapter.ability.utils;

import com.alibaba.cirtus.ots.application.adapter.ability.model.enums.MnSAPStatus;
import com.alibaba.citrus.ots.common.util.SpringContextUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MessageHeaderSDO;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SapRetrySaveRequest;
import com.epoch.app.otsapplicationadaptersdk.model.enums.RetryStatus;
import com.epoch.app.otsapplicationadaptersdk.model.enums.SapApiCode;
import com.epoch.app.otsapplicationadaptersdk.sap.*;
import com.epoch.app.otsapplicationadaptersdk.sapretrywrite.service.SapRetryWriteService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @description: SAP 返回
 * @author: yuhw
 * @date: 2021年10月22日 19:51
 **/
public class ResponseUtil {
    private static SapRetryWriteService sapRetryWriteService;
    static {
        sapRetryWriteService = SpringContextUtil.getBean(SapRetryWriteService.class);
    }
    private static Log log = Log.getLogger(ResponseUtil.class);


    public static MnSapCommResponse fail(MnSapIf008Request request,String message){
        MnSapCommResponse response = new MnSapCommResponse();
//        response.setMessageId(request.getMessageHeader()==null?null:request.getMessageHeader().getMessageId());
//        response.setInterfacePath(request.getMessageHeader()==null?request.getMessageHeader().getInterfacePath());
        response.setMessageId(Optional.ofNullable(request.getMessageHeader()).map(MessageHeaderSDO::getMessageId).orElse(null));
        response.setInterfacePath(Optional.ofNullable(request.getMessageHeader()).map(MessageHeaderSDO::getInterfacePath).orElse(null));
        if (CollectionUtils.isNotEmpty(request.getData())){
            List<MnSapCommSDO> data = Lists.newArrayList();
            for (MnSapIf008SDO sdo : request.getData()){
                MnSapCommSDO commSDO = new MnSapCommSDO();
                commSDO.setHeaderKey(sdo.getHeaderKey());
                commSDO.setMessage(message);
                commSDO.setErrCode(MnSAPStatus.ERROR.getCode());
                commSDO.setStatus(MnSAPStatus.ERROR.getCode());
                commSDO.setExtId(null);
                if (CollectionUtils.isNotEmpty(sdo.getItems())){
                    commSDO.setItem(sdo.getItems().stream().map(item->{
                        MnSapCommDetail commDetail = new MnSapCommDetail();
                        commDetail.setItemKey(item.getItem_key());
                        commDetail.setStatus(MnSAPStatus.ERROR.getCode());
                        commDetail.setMessage(message);
                        return commDetail;
                    }).collect(Collectors.toList()));
                }
                data.add(commSDO);
            }
            try {
                MnSapIf008SDO mnSapIf008SDO = request.getData().get(0);
                saveSapRetry(request,mnSapIf008SDO,message);
            }catch (Throwable e){
                log.error("ResponseUtil_saveError",e);
            }
            response.setData(data);
        }
        return response;
    }



    public static MnSapCommResponse fail(MnSapIf013Request request,String message){
        MnSapCommResponse response = new MnSapCommResponse();
//        response.setMessageId(request.getMessageHeader()==null?null:request.getMessageHeader().getMessageId());
//        response.setInterfacePath(request.getMessageHeader()==null?request.getMessageHeader().getInterfacePath());
        response.setMessageId(Optional.ofNullable(request.getMessageHeader()).map(MessageHeaderSDO::getMessageId).orElse(null));
        response.setInterfacePath(Optional.ofNullable(request.getMessageHeader()).map(MessageHeaderSDO::getInterfacePath).orElse(null));
        if (CollectionUtils.isNotEmpty(request.getData())){
            List<MnSapCommSDO> data = Lists.newArrayList();
            for (MnSapIf013SDO sdo : request.getData()){
                MnSapCommSDO commSDO = new MnSapCommSDO();
                commSDO.setHeaderKey(sdo.getHeaderKey());
                commSDO.setMessage(message);
                commSDO.setErrCode(MnSAPStatus.ERROR.getCode());
                commSDO.setStatus(MnSAPStatus.ERROR.getCode());
                commSDO.setExtId(null);
                if (CollectionUtils.isNotEmpty(sdo.getItems())){
                    commSDO.setItem(sdo.getItems().stream().map(item->{
                        MnSapCommDetail commDetail = new MnSapCommDetail();
                        commDetail.setItemKey(item.getItem_key());
                        commDetail.setStatus(MnSAPStatus.ERROR.getCode());
                        commDetail.setMessage(message);
                        return commDetail;
                    }).collect(Collectors.toList()));
                }
                data.add(commSDO);
            }
            try {
                MnSapIf013SDO mnSapIf013SDO = request.getData().get(0);
                saveSapRetry(request,mnSapIf013SDO,message);
            }catch (Throwable e){
                log.error("ResponseUtil_saveError",e);
            }
            response.setData(data);
        }
        return response;
    }

    public static MnSapCommResponse fail(MnSapIf017Request request,String message){
        MnSapCommResponse response = new MnSapCommResponse();
//        response.setMessageId(request.getMessageHeader()==null?null:request.getMessageHeader().getMessageId());
//        response.setInterfacePath(request.getMessageHeader()==null?request.getMessageHeader().getInterfacePath());
        response.setMessageId(Optional.ofNullable(request.getMessageHeader()).map(MessageHeaderSDO::getMessageId).orElse(null));
        response.setInterfacePath(Optional.ofNullable(request.getMessageHeader()).map(MessageHeaderSDO::getInterfacePath).orElse(null));
        if (CollectionUtils.isNotEmpty(request.getData())){
            List<MnSapCommSDO> data = Lists.newArrayList();
            for (MnSapIf017SDO sdo : request.getData()){
                MnSapCommSDO commSDO = new MnSapCommSDO();
                commSDO.setHeaderKey(sdo.getHeaderKey());
                commSDO.setMessage(message);
                commSDO.setErrCode(MnSAPStatus.ERROR.getCode());
                commSDO.setStatus(MnSAPStatus.ERROR.getCode());
                commSDO.setExtId(null);
                if (CollectionUtils.isNotEmpty(sdo.getItems())){
                    commSDO.setItem(sdo.getItems().stream().map(item->{
                        MnSapCommDetail commDetail = new MnSapCommDetail();
                        commDetail.setItemKey(item.getItem_key());
                        commDetail.setStatus(MnSAPStatus.ERROR.getCode());
                        commDetail.setMessage(message);
                        return commDetail;
                    }).collect(Collectors.toList()));
                }
                data.add(commSDO);
            }
            try {
                saveSapRetry(request,message);
            }catch (Throwable e){
                log.error("ResponseUtil_saveError",e);
            }
            response.setData(data);
        }
        return response;
    }

    public static MnSapCommResponse success(MnSapIf017Request request) {
        MnSapCommResponse mnSapCommResponse = new MnSapCommResponse();
        mnSapCommResponse.setMessageId(request.getMessageHeader().getMessageId());
        mnSapCommResponse.setInterfacePath(request.getMessageHeader().getInterfacePath());

        if (CollectionUtils.isNotEmpty(request.getData())) {
            List<MnSapCommSDO> data = Lists.newArrayList();
            for (MnSapIf017SDO sdo : request.getData()) {
                MnSapCommSDO commSDO = new MnSapCommSDO();
                commSDO.setHeaderKey(sdo.getHeaderKey());
                commSDO.setStatus("S");
                commSDO.setMessage("成功");
                if (CollectionUtils.isNotEmpty(sdo.getItems())) {
                    commSDO.setItem(sdo.getItems().stream().map(item -> {
                        MnSapCommDetail commDetail = new MnSapCommDetail();
                        commDetail.setItemKey(item.getItem_key());
                        commDetail.setStatus("S");
                        commDetail.setMessage("成功");
                        return commDetail;
                    }).collect(Collectors.toList()));
                }
                data.add(commSDO);
            }
            mnSapCommResponse.setData(data);
        }
        return mnSapCommResponse;
    }

    public static String deleteZeroPrefix(String str){
        if (StringUtils.isBlank(str))return null;
        return str.replaceFirst("^0*","");
    }


    /**
     * 保存sap重试记录
     *
     */
    public static void saveSapRetry(MnSapIf008Request request,MnSapIf008SDO sdo, String code){
        try{
            if (request == null ||StringUtils.isBlank(code) || code.startsWith("STO")){
                return;
            }
            SapRetrySaveRequest sapRetrySaveRequest = new SapRetrySaveRequest();
            String requestJson = JSON.toJSONString(request);
            sapRetrySaveRequest.setParam(requestJson);
            sapRetrySaveRequest.setMsg(code);
            sapRetrySaveRequest.setMessageId(request.getMessageHeader().getMessageId());
            //请求时间戳
            sapRetrySaveRequest.setRequestTime(sdo.getExt());
            sapRetrySaveRequest.setApiCode(SapApiCode.SAP008.getValue());
            sapRetrySaveRequest.setOutKey(sdo.getOutAllocateOrderId());
            sapRetrySaveRequest.setStatus(RetryStatus.FAIL.getValue());
            sapRetryWriteService.save(sapRetrySaveRequest);
        }catch (Throwable e){
            log.error("ResponseUtil_saveError",e);
        }
    }

    /**
     * 保存sap重试记录
     *
     */
    public static void saveSapRetry(MnSapIf013Request request,MnSapIf013SDO sdo, String code){
        try{
            if (request == null ||StringUtils.isBlank(code) || code.startsWith("STO")){
                return;
            }
            SapRetrySaveRequest sapRetrySaveRequest = new SapRetrySaveRequest();
            String requestJson = JSON.toJSONString(request);
            sapRetrySaveRequest.setParam(requestJson);
            sapRetrySaveRequest.setMsg(code);
            sapRetrySaveRequest.setMessageId(request.getMessageHeader().getMessageId());
            //请求时间戳
            sapRetrySaveRequest.setRequestTime(sdo.getExt());
            sapRetrySaveRequest.setApiCode(SapApiCode.SAP013.getValue());
            sapRetrySaveRequest.setOutKey(sdo.getOutAllocateOrderId());
            sapRetrySaveRequest.setStatus(RetryStatus.FAIL.getValue());
            sapRetryWriteService.save(sapRetrySaveRequest);
        }catch (Exception e){
            log.error("ResponseUtil_saveError",e);
        }
    }
    public static void saveSapRetry(MnSapIf017Request request, String message){
        try{
            if (request == null ||StringUtils.isBlank(message)){
                return;
            }
            SapRetrySaveRequest sapRetrySaveRequest = new SapRetrySaveRequest();
            String requestJson = JSON.toJSONString(request);
            sapRetrySaveRequest.setParam(requestJson);
            sapRetrySaveRequest.setMsg(message);
            sapRetrySaveRequest.setMessageId(request.getMessageHeader().getMessageId());
            //请求时间戳
            MnSapIf017SDO sdo = request.getData().get(0);
            sapRetrySaveRequest.setRequestTime(sdo.getExt1());
            sapRetrySaveRequest.setApiCode(SapApiCode.SAP017.getValue());
            sapRetrySaveRequest.setOutKey(sdo.getDeliveryOrderId());
            sapRetrySaveRequest.setStatus(RetryStatus.FAIL.getValue());
            sapRetryWriteService.save(sapRetrySaveRequest);
        }catch (Exception e){
            log.error("ResponseUtil_saveError",e);
        }
    }

    //校验时间戳字段 空值 格式
    public static String check(String time){
        //修改时间 格式为20220307111350.3513180 前面年月日时分秒 后面是 0.3513180
        if (StringUtils.isBlank(time)){
            return "时间戳字段值不能为空";
        }else {
            String[] split = time.split("\\.");
            if (split.length != 2){
                return "时间戳字段值格式错误";
            }
        }
        return null;
    }

}
